package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result<String> onException(BaseException baseException){
        String message = baseException.getMessage();
        log.info("发生异常了："+message);
        return Result.error(message);
    }

    @ExceptionHandler
    public Result<String> onDuplicateEntry(SQLIntegrityConstraintViolationException exception){
        String message = exception.getMessage();
        if(message.contains("Duplicate entry")){
            String[] s = message.split(" ");
            String name=s[2];
            return Result.error(name+MessageConstant.DUPLICATE);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
